/**
 * Copyright (c) 2014-2016 www.nryuncang.com. All Rights Reserved.
 */
package com.topisv.tms.web.unprocessxml;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springside.modules.web.Servlets;

import com.topisv.tms.entity.AreaGroup;
import com.topisv.tms.entity.Customers;
import com.topisv.tms.entity.qimen.DeliveryOrderTask;
import com.topisv.tms.entity.qimen.OrderProcessConfig;
import com.topisv.tms.service.AreaGroupService;
import com.topisv.tms.service.CustomersService;
import com.topisv.tms.service.account.ShiroDbRealm.ShiroUser;
import com.topisv.tms.service.qimen.DeliveryOrderTaskService;
import com.topisv.tms.service.unprocessxml.UnProcessXmlService;
import com.topisv.tms.task.DeliveryOrderTaskProvider;

/**
 * 
 *
 * @author <a href=mailto:zhangweize@nryuncang.com>zhangweize</a>
 * @version 1.0.0
 */
@Controller
@RequestMapping(value = "/v2/unProcessXml")
@SuppressWarnings({ "unchecked", "unused", "rawtypes", "serial" })
public class UnProcessXmlController {
	private static final Logger logger = LoggerFactory.getLogger(UnProcessXmlController.class);

	@Autowired
	private AreaGroupService areaGroupService;
	@Autowired
	private UnProcessXmlService unProcessXmlService;
	@Autowired
	private CustomersService customersService;
	@Autowired
	private DeliveryOrderTaskService deliveryOrderTaskService;

	

	/**
	 * 页面初始化
	 * 
	 *
	 * @param model
	 * @return [参数说明]
	 * @author <a href=mailto:zhangweize@nryuncang.com>zhangweize</a>
	 * @version 1.0.0
	 */
	@RequestMapping(value = "query")
	public String query(Model model) {
		
		// 查询所有仓库
		List<AreaGroup> allWarehouseList = areaGroupService.findAll();
		model.addAttribute("allWarehouseList", allWarehouseList);

		// 查出当前用户关联的商家列表
		ShiroUser curUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
		List<Customers> customerList = customersService.loadCustomerByAuthority(curUser);
		model.addAttribute("customerList", customerList);

		return "unprocessxml/unProcessXml";
	}
	
	/**
	 * 
	 * 统计每个仓库的未处理报文数量、待处理订单数量、待处理订单数量
	 *
	 * @param request
	 * @param response
	 * @return [参数说明]
	 * @author <a href=mailto:zhangweize@nryuncang.com>zhangweize</a>
	 * @version 1.0.0
	 */
	@RequestMapping(value = "queryCountOrder")
	public String queryCountOrder(Model model, HttpServletRequest request, HttpServletResponse response) {
		try {
            Map<String, Object> searchParams = Servlets.getParametersStartingWith(request, "_");
			String warehouseCode = (String) searchParams.get("warehouseCode");
			String customerCode = (String) searchParams.get("customerCode");
			String fromDate = (String) searchParams.get("fromDate");

			Map<String, Object> param = new HashMap<String, Object>();
			
			// 所有仓库
			 List<AreaGroup> warehouseList = areaGroupService.findAll();
			model.addAttribute("allWarehouseList", warehouseList);
			param.put("warehouseCode", warehouseCode);
			param.put("fromDate", fromDate+" 00:00:00");
			param.put("toDate", fromDate+" 23:59:59");
			// 查询DeliveryOrderTask表统计每个仓库中未处理的报文数量
			Map<String, Map<String, Long>> deliveryOrderTaskMap = unProcessXmlService.loadDeliveryOrderTaskMap(param);

			// 查询EdiOrder表统计每个仓库中待处理订单数量
			param.put("dispatchFlag", "1");
			Map<String, Map<String, Long>> waitProcessEdiOrderMap = unProcessXmlService.loadEdiOrderMap(param);

			// 查询EdiOrder表统计每个仓库中不可处理订单数量
			param.put("dispatchFlag", "0");
			Map<String, Map<String, Long>> unProcessEdiOrderMap = unProcessXmlService.loadEdiOrderMap(param);

			for(AreaGroup warehouse : warehouseList){
				warehouse.setUnProcessXmlNum(deliveryOrderTaskMap.get(warehouse.getGroupCode()) == null ? 0L:deliveryOrderTaskMap.get(warehouse.getGroupCode()).get("num"));
				warehouse.setUnProcessOrderNum(unProcessEdiOrderMap.get(warehouse.getGroupCode()) == null ? 0L:unProcessEdiOrderMap.get(warehouse.getGroupCode()).get("num"));
				warehouse.setWaitProcessOrderNum(waitProcessEdiOrderMap.get(warehouse.getGroupCode()) == null ? 0L:waitProcessEdiOrderMap.get(warehouse.getGroupCode()).get("num"));
			}
			
			//仓库列表
            model.addAttribute("warehouseCode", warehouseCode);
            model.addAttribute("customerCode", customerCode);
            
			// 查出当前用户关联的商家列表
			ShiroUser curUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
			List<Customers> customerList = customersService.loadCustomerByAuthority(curUser);
			model.addAttribute("customerList", customerList);
			
			model.addAttribute("warehouseNumList", warehouseList);
			
		} catch (Exception e) {
			logger.error("统计每个仓库的未处理报文数量、待处理订单数量、待处理订单数量error:{}", e);
		}
		return "unprocessxml/unProcessXml";
	}
	
	/**
	 * 手动处理订单
	 * 
	 *
	 * @param model
	 * @param request
	 * @param response [参数说明]
	 * @author <a href=mailto:zhangweize@nryuncang.com>zhangweize</a>
	 * @version 1.0.0
	 */
	@RequestMapping(value = "processXml")
	public String processXml(Model model, HttpServletRequest request, HttpServletResponse response) {
		
		try {
			Map<String, Object> searchParams = Servlets.getParametersStartingWith(request, "_");
			String warehouseCode = (String) searchParams.get("warehouseCode");
			String customerCode = (String) searchParams.get("customerCode");
			String limitNum =(String) searchParams.get("num");

			String msg = "提交成功!";
			// 查询所有仓库
			List<AreaGroup> allWarehouseList = areaGroupService.findAll();
			model.addAttribute("allWarehouseList", allWarehouseList);

			// 查出当前用户关联的商家列表
			ShiroUser curUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
			List<Customers> customerList = customersService.loadCustomerByAuthority(curUser);
			model.addAttribute("customerList", customerList);

			Map<String, Object> param = new HashMap<String, Object>();
			param.put("warehouseCode", warehouseCode);
			param.put("dispatchFlag", "1");
			
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			
			String fromDate = sdf.format(DeliveryOrderTaskService.getDateBefore(new Date(), 6))+" 00:00:00";
			String  toDate = sdf.format(new Date())+" 23:59:59";
			
			param.put("fromDate", fromDate);
			param.put("toDate", toDate);
			
			OrderProcessConfig orderProcessConfig = deliveryOrderTaskService.findOrderProcessConfigByWarehouse(warehouseCode);
			if (orderProcessConfig != null) {
				if (unProcessXmlService.isMeetWaitOrderNumlessThreshold(param, orderProcessConfig)) {
					unProcessXmlService.sendTask(orderProcessConfig, customerCode, limitNum, fromDate, toDate);
				}else {
					msg = "该仓库中的待处理订单数量超过了阀值,不进行处理!";
				}
			}else {
				msg = "订单处理配置中没有该仓库的配置记录";
			}
			model.addAttribute("message", msg);
		} catch (Exception e) {
			logger.error("手动处理订单error:{}", e);
			model.addAttribute("message", "提交失败!");
	   }
		return "unprocessxml/unProcessXml";
	}
	
	/**
	 * 重定向ip
	 * 
	 *
	 * @param model
	 * @param request
	 * @param response [参数说明]
	 * @author <a href=mailto:zhangweize@nryuncang.com>zhangweize</a>
	 * @version 1.0.0
	 */
	@RequestMapping(value = "redirectDealIp")
	public void redirectDealIp(Model model, HttpServletRequest request, HttpServletResponse response){
		try{
			Map<String, Object> searchParams = Servlets.getParametersStartingWith(request, "_");
			List<DeliveryOrderTask> dataList = new ArrayList<>();

			String warehouseCode = (String) searchParams.get("warehouseCode");
			String customerCode = (String) searchParams.get("customerCode");
			int limitNum = Integer.valueOf((String) searchParams.get("num"));
			String fromDate = (String) searchParams.get("fromDate");
			String toDate = (String) searchParams.get("toDate");
			
			// 根据仓库，商家 ，限制条数 手动锁数据
			deliveryOrderTaskService.manualLockData(warehouseCode, customerCode, limitNum, fromDate, toDate);

			// 查询报文数据
			if (StringUtils.isNotBlank(customerCode)) {
				dataList = deliveryOrderTaskService.manualFindData(warehouseCode, customerCode);
			} else {
				dataList = deliveryOrderTaskService.findData(warehouseCode);
			}
			
			DeliveryOrderTaskProvider.putTaskQueue(warehouseCode, dataList);
		} catch (Exception e) {
			logger.error(" 重定向ip.", e);
		}
	}
		
	
	
	
}
